<?php
declare (strict_types = 1);

namespace app\common\model;

class Cate extends Base
{

    protected $name = 'cate';

    public static function getAll()
    {
        try {

            $result = parent::order('sort', 'asc')->select()->toArray();
            return self::mergeMenu($result);

        } catch (\Exception $e) {
            return [];
        }
    }

    public function child()
    {
        return $this->hasMany(Cate::class, 'pid')
            ->field('id,pid,title');
    }

    public static function getCate($id = 0)
    {
        return parent::where(['pid' => $id,'status' => 1])
            ->field("id,title")->order('sort')->select();
    }

    public static function mergeMenu($cate, $pid = 0, $lvl = 0, $left_px = 0)
    {
        $arr = array();

        foreach ($cate as $v) {
            if ($v['pid'] == $pid) {
                $v['lvl'] = $lvl + 1;
                $v['left_px'] = $left_px + 0;//左边距
                $arr[] = $v;
                $arr = array_merge($arr, mergeMenu($cate, $v['id'], $lvl + 1, $left_px + 40));
            }
        }
        return $arr;
    }
    /**
     * 保存
     */
    public static function saveCate($param){
        try {
            
            $radio_count = Exam::where(['types'=>1,'cate'=>$param['id']])->count();
            if($param['radio_num']>$radio_count){
                return ['code'=>-1,'msg'=>'单选题库数量不足！'];
            }
            $check_count = Exam::where(['types'=>2,'cate'=>$param['id']])->count();
            if($param['check_num']>$check_count){
                return ['code'=>-1,'msg'=>'多选题库数量不足！'];
            }
            $num = $param['radio_num'] * $param['radio_score'] + $param['check_num'] * $param['check_score'];
            if($num !=100){
                return ['code'=>-1,'msg'=>'满分必须100分！当前总分：'.$num];
            }
            $info = parent::find($param['id']);
            $info->radio_num = $param['radio_num'];
            $info->radio_score = $param['radio_score'];
            $info->check_num = $param['check_num'];
            $info->check_score = $param['check_score'];
            $info->save();
            return ['code'=>1,'msg'=>'保存成功'];
        }catch (\Exception $e) {
            return ['code'=>-1,'msg'=>$e->getMessage()];
        }
    }

}
